<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #calendar {
        display: flex;
        width: 140px;
        border: solid 1px;
        flex-wrap: wrap;
        font-size: 12px;
      }

      #calendar > div {
        width: 20px;
        height: 20px;
        display: flex;
        justify-content: center;
        align-items: center;
        border: solid 1px;
        box-sizing: border-box;
      }
    </style>
  </head>
  <body>
    <div id="calendar">
      <div>一</div>
      <div>二</div>
      <div>三</div>
      <div>四</div>
      <div>五</div>
      <div>六</div>
      <div>日</div>
    </div>
    <script>
      function createCalendar(year, month, node) {
        //-----
        const d0 = new Date(year, month - 1, 1).getDay() || 7;
        const dx = new Date(year, month - 1, 0).getDate();
        const a0 = new DocumentFragment();
        for (let i = d0 - 2; i >= 0; i--) {
          const div = document.createElement("div");
          div.innerText = 30 - i;
          a0.append(div);
        }
        node.append(a0);
        // month一共多少天----
        const d1 = new Date(year, month, 0).getDate();
        const a1 = new DocumentFragment();
        for (let i = 1; i <= d1; i++) {
          const div = document.createElement("div");
          div.innerText = i;
          a1.append(div);
        }
        node.append(a1);

        // ----
        const d2 = new Date(year, month, 0).getDay() || 7;
        const a2 = new DocumentFragment();
        for (let i = 1; i <= 7 - d2; i++) {
          const div = document.createElement("div");
          div.innerText = i;
          a2.append(div);
        }
        node.append(a2);
      }
      createCalendar(2024, 5, document.getElementById("calendar"));
    </script>
  </body>
</html>
